package com.bluewap.core;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;

import com.jolbox.bonecp.BoneCP;
import com.jolbox.bonecp.BoneCPConfig;

public class Database {
	private static Logger log = Logger.getLogger("db");
	
	private static String className = "com.mysql.jdbc.Driver";
	private static String url = "jdbc:mysql://123.30.235.21:3306/bluewap";
	private static String username = "root";
	private static String password = "thanhnvcti";
	private static String testSql = "SELECT 1 from dual";
	private static int minPool = 5;
	private static int maxPool = 20;
	
	private static BoneCP pool = null;

	public static void releasePool(){
		if(pool != null)
			pool.shutdown();
	}

	private static void initPool(){
		try {
			Class.forName(className);
			BoneCPConfig config = new BoneCPConfig();
			
			Configuration configuration = Configuration.getInstance();
			try {
				Properties prop = configuration.loadFile("database.properties");
				url = prop.getProperty("dburl");
				username = prop.getProperty("dbusername");
				password = prop.getProperty("dbpassword");
				minPool = Integer.parseInt(prop.getProperty("minPool"));
				maxPool = Integer.parseInt(prop.getProperty("maxPool"));
			} catch (FileNotFoundException e) {
				log.error("Error", e);
			} catch (IOException e) {
				log.error("Error", e);
			}
			
			config.setJdbcUrl(url);
			config.setUsername(username);
			config.setPassword(password);

			config.setConnectionTimeout(5, TimeUnit.MINUTES);
			config.setIdleConnectionTestPeriod(1, TimeUnit.MINUTES);

			config.setConnectionTestStatement(testSql);
			config.setMinConnectionsPerPartition(minPool);
			config.setMaxConnectionsPerPartition(maxPool);
			config.setMaxConnectionAge(60, TimeUnit.HOURS);

			config.setPartitionCount(1);
			pool = new BoneCP(config);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			log.error("Error", e);
		} catch (SQLException e) {
			e.printStackTrace();			
			log.error("Error", e);
		}
	}

	public static void closeConnection(Connection conn){
		try {
			conn.close();
		} catch (SQLException e) {
			log.error("Error", e);
		}
	}

	public static Connection getConnection(){
		if(pool == null)
			initPool();
		Connection conn = null;
		int retry = 0;
		while(conn == null && retry < 10){
			try {
				conn = pool.getConnection();
			} catch (SQLException e) {
				log.error("Error", e);
			}
			if(conn == null){
				try {
					Thread.sleep(1000);
					retry ++;
				} catch (InterruptedException e) {
					log.error("Error", e);
				}
			}
		}
		return conn;
	}
}
